import dgram from 'dgram';

class IUdpManager {

  public start: ((port: number) => void) | undefined;

  public stop: (() => void) | undefined;

  public getLastMessage: (() => string) | undefined;
}

class UdpManager extends IUdpManager {

  private socket: any;

  private lastMessage: string = '';

  public getLastMessage = (): string => {
    return this.lastMessage;
  }

  public start = (port: number): void => {
    this.socket = dgram.createSocket('udp4');

    this.socket.on('message', (msg) => {
      this.lastMessage = msg.toString();
    });

    this.socket.bind(port);
  }

  public stop = (): void => {
    this.socket.close();
  }

}

const udpManager = new UdpManager();

export default udpManager;
